package web;
/*
控制层：控制用户登录
如果用户名和密码输入错误，返回false
如果成功登录返回ture，将成功登录用户数据传入至设置session的Servlet中，并跳转至学生信息界面
 */
import com.fasterxml.jackson.databind.ObjectMapper;
import service.LoggingCheckService;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class LoggingServlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
//            req.setCharacterEncoding("UTF-8");
//            resp.setContentType("text/html;charset=utf-8");
            System.out.println("LoggingServlet服务器接收到客户端的登录请求");
            //1.获取前台的参数username,password
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            //2.调用service的loggingCheckService方法，返回boolean值
            boolean flag = new LoggingCheckService().loggingCheckService(username,password);
            //3.创建一个map对象，给map中设置内容
            Map<String, Object> map = new HashMap<>();
            //4.map转成json返回前台
            ObjectMapper om = new ObjectMapper();
            if(flag){
                map.put("pass", true);
                map.put("msg", "登录成功！");
            }else{
                map.put("pass",false);
                map.put("msg", "登录失败，请检查用户名或者密码是否输入错误。");
            }
            String mapJson = om.writeValueAsString(map);
            //5.json数据返回给前台
            resp.getWriter().println(mapJson);
            System.out.println(mapJson);
            req.setAttribute("logging",false);
            if(flag){
            //将成功登录的用户存入request域中以方便将用户信息存入session域中
            req.setAttribute("logging",true);
            req.setAttribute("mapJson",mapJson);
//                req.setAttribute("password",password);
            //获得转发器对象，并转发至setSession
            RequestDispatcher path = req.getRequestDispatcher("/setSession");
            path.forward(req,resp);}

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
